#!/usr/bin/env ruby
# -*- coding: us-ascii -*-
# Elizabeth Wiethoff 2008

require File.join(File.dirname(__FILE__), 'osdetect')

########################################

# from "Ruby Cookbook," recipe 6.13: "Locking a File"
def flock(file, mode, &block)
  success = file.flock(mode)
  if success
    begin
      yield file
    ensure
      file.flock(File::LOCK_UN)
    end
  end
  return success
end

# from "Ruby Cookbook," recipe 6.13: "Locking a File"
def open_lock(filename, openmode='r', lockmode=nil, &block)
  if openmode == 'r' || openmode == 'rb' 
    lockmode ||= File::LOCK_SH
  else
    lockmode ||= File::LOCK_EX
  end
  
  value = nil
  open(filename, openmode) do |f|
  flock(f, lockmode) do
    begin
      value = yield f
    ensure
      f.flock(File::LOCK_UN) unless $MSWIN
    end
  end
  return value
  end
end
